package jbitarrays;

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;

import jbitarrays.api.CrawlerWriter;
import jbitarrays.api.InfiniteBitArray;

/**
 * @see JBitArrays#startWriting(InfiniteBitArray, int)
 */
@NotThreadSafe final class DefaultCrawlerWriter implements CrawlerWriter {
	private final InfiniteBitArray array;
	private int index;

	public DefaultCrawlerWriter(@Nonnull InfiniteBitArray array) {
		this(array, 0);
	}

	public DefaultCrawlerWriter(@Nonnull InfiniteBitArray array, @Nonnegative int index) {
		if (array == null || index < 0) {
			throw new IllegalArgumentException("array != null && index >= 0");
		}
		this.array = array;
		this.index = index;
	}

	public void setNext(boolean value) {
		array.set(index++, value);
	}

	public void setNextN(int howMany, int value) {
		Utils.checkHowMany(howMany);
		array.setN(index, howMany, value);
		index += howMany;
	}

	@Override public CrawlerWriter clone() {
		return new DefaultCrawlerWriter(array, index);
	}

	public DefaultCrawlerReader toReader() {
		return new DefaultCrawlerReader(array, index);
	}
}
